<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '/@/views/system/department/data';
  import { addDepartment, getDepartmentList, updateDepartment } from '/@/api/sys/department';
  import { transformTreeData } from '/@/utils/helper/transformTreeData';

  const isUpdate = ref(true);
  const emits = defineEmits(['success', 'register']);
  const department_id = ref(null);

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      await setFieldsValue({
        ...data.record,
      });
      department_id.value = data.record.id;
    }
    const treeData = await getDepartmentList();
    transformTreeData(treeData, isUpdate, data);
    await updateSchema({
      field: 'parent_id',
      componentProps: {
        treeData,
        fieldNames: {
          label: 'name',
          key: 'id',
          value: 'id',
        },
      },
    });
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增部门' : '编辑部门'));

  const handleSubmit = async () => {
    try {
      let value = await validate();
      value['id'] = department_id.value;
      setModalProps({ confirmLoading: true });
      if (!unref(isUpdate)) {
        await addDepartment(value);
      } else {
        await updateDepartment(value);
      }
      emits('success');
      closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  };
</script>

<style scoped lang="less"></style>
